package com.bookmall.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.sql.DataSource;

import com.alibaba.druid.pool.DruidDataSource;

public class DBUtil {
	// 1.创建一个数据源
	private static DataSource ds;
	// 2.静态块
	static {
		try {
			Properties pro = new Properties();
			pro.load(new FileInputStream("jdbc.properties"));
			String driver = pro.getProperty("jdbc.driver");
			String url = pro.getProperty("jdbc.url");
			String name = pro.getProperty("jdbc.username");
			String pwd = pro.getProperty("jdbc.password");

			DruidDataSource dds = new DruidDataSource();
			dds.setDriverClassName(driver);
			dds.setUrl(url);
			dds.setUsername(name);
			dds.setPassword(pwd);
			dds.setInitialSize(10);
			dds.setMinIdle(10);
			dds.setMaxActive(20);
			dds.setLoginTimeout(30);
			// 赋值给sql的数据源
			ds = dds;

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 返回一个连接
	public static Connection getConnection() {
		try {
			return ds.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	// 关闭连接
	public static void closeConnection(Connection c, Statement s, ResultSet rs) {
		try {
			if (rs != null) {
				rs.close();
			}
			if (s != null) {
				s.close();
			}
			if (c != null) {
				c.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
